package com.icode.core.shared;

import com.icode.core.model.house.UploadImage;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sunk
 * Date: 15-1-23
 * Time: 上午11:44
 * To change this template use File | Settings | File Templates.
 */
public class ImageUtils {

    public static List<UploadImage> resolveUploadImages(List<MultipartFile> list) {
        List<UploadImage> documents = new ArrayList<>();
        for (MultipartFile file : list) {
            UploadImage document = MultipartFileToUploadImage(file);
            documents.add(document);
        }
        return documents;
    }

    public static void showImageByContents(byte[] contents, HttpServletResponse response) {
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(contents);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static UploadImage MultipartFileToUploadImage(MultipartFile m) {
        UploadImage document = null;
        try {
            String imageName = m.getName();
            String contentType = m.getContentType();
            byte[] bytes = m.getBytes();
            document = new UploadImage(imageName, contentType, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    }

//    public static byte[] decoderBase64ToByte(String base64Code) {
//        if (StringUtils.isEmpty(base64Code)) {
//            return null;
//        }
//        BASE64Decoder decoder = new BASE64Decoder();
//        byte[] b = null;
//        try {
//            b = decoder.decodeBuffer(base64Code); //Base64解码
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {
//                    b[i] += 256;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return b;
//    }
//
//    public static String decoderToBase64(byte[] contents) {
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(contents);  //返回Base64编码过的字节数组字符串
//    }

    public static void resize(int w, int h, Image img, HttpServletResponse response) throws IOException {
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, w, h, null);
        OutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }

}
